package com.herui.ota.service.iml;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.herui.ota.dao.mysql.UserAdminMapper;
import com.herui.ota.entity.UserAdmin;
import com.herui.ota.enums.UserIdentityEnum;
import com.herui.ota.pojo.form.UserAdminFilterForm;
import com.herui.ota.pojo.form.UserAdminForm;
import com.herui.ota.pojo.vo.UserAdminVo;
import com.herui.ota.service.UserAdminService;
import com.mlnx.common.form.PageForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;

/**
 * author name: amanda.shan
 * create time: 2023-05-19 17:57:17
 */ 
@Service
public class UserAdminServiceIml extends BaseService<UserAdminMapper, UserAdmin> implements UserAdminService {

	@Autowired
	PasswordEncoder passwordEncoder;

	@Autowired
	@Override
	public void setBaseMapper(UserAdminMapper baseMapper) {
		super.setBaseMapper(baseMapper);
	}

	@Override
	public IPage page(PageForm pageForm, Object filter) throws IllegalAccessException {
		Page<UserAdminVo> userAdminVoPage = baseMapper.listUserAdminVoPage(new Page<>(pageForm.getCurrent(),
				pageForm.getSize()), (UserAdminFilterForm) filter);
		userAdminVoPage.getRecords().stream().forEach(userAdminVo -> userAdminVo.setLock(lightUserAccountServiceIml.isLock(userAdminVo.getId())));
		return userAdminVoPage;
	}

	@Transactional
	@Override
	public void save(UserAdminForm userAdminForm) {
		checkRight("user_edit");
		int id = saveAccount(userAdminForm.getUsername(), userAdminForm.getPassword(), userAdminForm.getRoleId(),
				UserIdentityEnum.ADMIN.toString());
		// 保存数据
		UserAdmin userAdmin = new UserAdmin();
		BeanUtils.copyProperties(userAdminForm, userAdmin);
		userAdmin.setId(id);
		super.save(wrapperCreater(userAdmin));
	}

	@Transactional
	@Override
	public void update(Integer id, UserAdminForm form) {
		checkRight("user_edit");
		// 更新用户信息
		UserAdmin userAdmin = new UserAdmin();
		BeanUtils.copyProperties(form, userAdmin);
		userAdmin.setId(id);
		updateById(wrapperEditor(userAdmin));

		// 更改用户角色 密码
		Integer roleId = form.getRoleId();
		String password = form.getPassword();
		if (!StringUtils.isEmpty(password)){
			password = passwordEncoder.encode(form.getPassword());
		}
		updateAccount(id, password, roleId);
	}

	@Override
	public boolean removeById(Serializable id) {
		checkRight("user_edit");
		return super.removeById(id);
	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {
		checkRight("user_edit");
		return super.removeByIds(idList);
	}
}

